<template>
<section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="filters">
            <el-form-item>
                <el-input v-model="filters.userName" placeholder="病人姓名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-date-picker type="date" placeholder="诊断日期" v-model="filters.createTime" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" v-on:click="queryCaseInfoByPage">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" v-if="userType == '1'" @click="handleAdd">开始诊断</el-button>
            </el-form-item>
            <div id="divform"></div>
        </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="users" highlight-current-row v-loading="listLoading" style="width: 100%;">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="userName" label="病人姓名" sortable></el-table-column>
        <el-table-column prop="sex" label="性别" :formatter="formatSex" sortable></el-table-column>
        <el-table-column prop="age" label="年龄" sortable></el-table-column>
        <el-table-column prop="phoneNumber" label="电话号码" sortable></el-table-column>
        <el-table-column prop="diagnostic" label="诊断" :formatter="formatterDiagnostic" sortable></el-table-column>
        <el-table-column prop="doctorOrder" label="医嘱" :formatter="formatterOrder" sortable></el-table-column>
        <el-table-column prop="medicines" label="开药" :formatter="formatterMedicines" sortable></el-table-column>
        <el-table-column prop="caseStatus" label="状态" :formatter="formatterStatus" sortable></el-table-column>
        <el-table-column label="操作" width="200">
            <template slot-scope="scope">
                <el-button type="primary" size="small" v-if="userType == '1'" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="primary" size="small" v-if="scope.row.medicines && userType == '2' && scope.row.caseStatus != '1'" @click="handleEnd(scope.$index, scope.row)">线上支付</el-button>
                <el-button type="primary" size="small" v-if="scope.row.medicines && userType == '2' && scope.row.caseStatus != '1'" @click="handleEnd1(scope.$index, scope.row)">线下支付</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
        <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="size" :total="total" style="float:right;"></el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog title="编辑" :visible.sync="addFormVisible" :close-on-click-modal="false">
        <el-form :model="addForm" label-width="80px" :rules="editFormRules" ref="addForm">
            <el-form-item label="挂号病人">
                <el-autocomplete v-model="addForm.userName" style="width:100%;" :fetch-suggestions="queryRegisteredUserByDoctorId" @select="handleSelect"></el-autocomplete>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click.native="addFormVisible = false">取消</el-button>
            <el-button type="primary" @click.native="addSubmit" :loading="editLoading">提交</el-button>
        </div>
    </el-dialog>

    <!--编辑界面-->
    <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
        <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
            <el-form-item label="病人姓名" prop="userName">
                <el-input v-model="editForm.userName" readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item label="诊断" prop="diagnostic">
                <el-input v-model="editForm.diagnostic" type="textarea" :rows="5"></el-input>
            </el-form-item>
            <el-form-item label="医嘱" prop="doctorOrder">
                <el-input v-model="editForm.doctorOrder" type="textarea" :rows="5"></el-input>
            </el-form-item>
            <el-form-item label="添加药品">
                <el-button type="success" @click="appendMedicine()">添加药品</el-button>
            </el-form-item>
            <el-form-item label="开药" v-for="(medicine,index) in editForm.medicineList" :key="medicine.key">
                <el-autocomplete v-model="editForm.medicineList[index].medicineName" style="width:100%;" :fetch-suggestions="queryMedicine" placeholder="药品名称" @select="((item)=>{handleSelectMedicine(item, index)})"></el-autocomplete>
                <el-input-number v-model="editForm.medicineList[index].amount" :min="1"></el-input-number>
                <el-input v-model="editForm.medicineList[index].remark" placeholder="用法用量"></el-input>
                <el-button @click="deleteAuto(index)">删除</el-button>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click.native="editFormVisible = false">取消</el-button>
            <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
        </div>
    </el-dialog>
</section>
</template>

<script>
import {
    mapGetters
} from "vuex";
import * as api from "@/api/api.js";
import {
    parse
} from "path";
import axios from "axios";
const Qs = require('qs');

export default {
    data() {
        return {
            defaultProps: {
                children: "children",
                label: "nodeName"
            },
            filters: {
                userName: "",
                createTime: null
            },
            showUrl: api.showUrl,
            uploadFileUrl: api.uploadFileUrl,
            users: [],
            total: 0,
            current: 1,
            size: 10,
            listLoading: false,
            sels: [], //列表选中列
            editFormVisible: false, //编辑界面是否显示
            addFormVisible: false,
            editLoading: false,
            editFormRules: {},
            //编辑界面数据
            editForm: {},
            addForm: {},
            tempId: 0,
            userType: "",
        };
    },
    computed: {
        ...mapGetters("user", ["getUser"])
    },
    methods: {
        formatSex: function (row, column) {
            return row.sex == "1" ? "男" : "女";
        },
        formatterStatus: function (row, column) {
            return row.caseStatus == "1" ? "已结束" : "诊断中";
        },
        formatterOrder(row, column) {
            return row.doctorOrder && row.doctorOrder.length > 10 ? row.doctorOrder.substring(0, 10) + "..." : row.doctorOrder;
        },
        formatterDiagnostic(row, column) {
            return row.diagnostic && row.diagnostic.length > 10 ? row.diagnostic.substring(0, 10) + "..." : row.diagnostic;
        },
        formatterMedicines(row, column) {
            return row.medicines ? row.medicines.substring(0, row.medicines.length - 1) : "";
        },
        handleCurrentChange(val) {
            this.current = val;
            this.queryCaseInfoByPage();
        },
        //获取列表
        queryCaseInfoByPage() {
            let para = {
                current: this.current,
                size: this.size,
                userName: this.filters.userName,
                createTime: this.filters.createTime
            };
            if (this.userType == '1') {
                para.doctorId = this.getUser.userId;
            }
            this.listLoading = true;
            api.queryCaseInfoByPage(para)
                .then(res => {
                    this.total = res.returnPage.total;
                    this.users = res.returnPage.records;
                    this.listLoading = false;
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        //删除
        handleDel: function (index, row) {
            this.$confirm("确认删除该记录吗?", "提示", {
                    type: "warning"
                })
                .then(() => {
                    this.listLoading = true;
                    let para = {
                        userId: row.userId
                    };
                    api.delUser(para).then(res => {
                        this.listLoading = false;
                        if (res.message == 'success') {
                            this.$message({
                                message: "删除成功",
                                type: "success"
                            });
                        }
                        this.queryCaseInfoByPage();
                    });
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        //显示编辑界面
        handleEdit: function (index, row) {
            this.editFormVisible = true;
            this.editForm = Object.assign({}, row);
        },
        handleEnd: function (index, row) {
            let medicineNames = "";
            let money = 0;
            medicineNames += row.medicines.substring(0, row.medicines.length - 1) + ",";
            for (let i = 0; i < row.medicineList.length; i++) {
                money += (parseFloat(row.medicineList[i].price) * parseFloat(row.medicineList[i].amount));
            }

            axios.post(
                    api.url + "/alipay/payment",
                    Qs.stringify({ //将对象 序列化成URL的形式，以&进行拼接
                        orderId: row.caseInfoId,
                        subject: row.userName + "的药费",
                        body: "购买药品：" + medicineNames.substring(0, medicineNames.length - 1),
                        money: money,
                    }), {
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded", //通过POST方式以页面表单方式提交数据到接口
                        },
                    }
                )
                .then((res) => {
                    let divForm = document.getElementById("divform");
                    if (divForm.length) {
                        document.body.removeChild(divForm[0]);
                    }
                    const div = document.createElement("divform");
                    div.innerHTML = res.data;
                    document.body.appendChild(div);
                    document.getElementsByName("punchout_form")[0].submit();
                })
                .catch((error, status) => {
                    console.log(error);
                });
        },
        handleEnd1: function (index, row) {
            let para = Object.assign({}, row);
            api.caseInfoPay(para)
                .then(res => {
                    if (res.message == 'success') {
                        this.$message({
                            message: "提交成功",
                            type: "success"
                        });
                        this.queryCaseInfoByPage();
                    }
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        //显示新增界面
        handleAdd: function () {
            this.addFormVisible = true;
            this.addForm = {};
        },
        //新增
        addSubmit: function () {
            this.$refs.addForm.validate(valid => {
                if (valid) {
                    this.$confirm("确认提交吗？", "提示", {}).then(() => {
                        this.editLoading = true;
                        let para = Object.assign({}, this.addForm);
                        para.doctorId = this.getUser.userId

                        api.updateCaseInfo(para)
                            .then(res => {
                                this.editLoading = false;
                                if (res.message == 'success') {
                                    this.$message({
                                        message: "提交成功",
                                        type: "success"
                                    });
                                    // this.$refs["addForm"].resetFields();
                                    this.addFormVisible = false;
                                    this.queryCaseInfoByPage();
                                }
                            })
                            .catch(() => {
                                this.listLoading = false;
                            });
                    });
                }
            });
        },
        //编辑
        editSubmit: function () {
            this.$refs.editForm.validate(valid => {
                if (valid) {
                    this.$confirm("确认提交吗？", "提示", {}).then(() => {
                        this.editLoading = true;
                        let para = Object.assign({}, this.editForm);
                        api.updateCaseInfo(para)
                            .then(res => {
                                this.editLoading = false;
                                if (res.message == 'success') {
                                    this.$message({
                                        message: "提交成功",
                                        type: "success"
                                    });
                                    this.$refs["editForm"].resetFields();
                                    this.editFormVisible = false;
                                    this.queryCaseInfoByPage();
                                }
                            })
                            .catch(() => {
                                this.listLoading = false;
                            });
                    });
                }
            });
        },
        queryRegisteredUserByDoctorId(queryString, callback) {
            let para = {
                userType: '3',
                userName: queryString,
                doctorId: this.getUser.userId
            };
            api.queryRegisteredUserByDoctorId(para)
                .then(res => {
                    let list = res.returnList.map(item => {
                        item.value = item.userName
                        return item;
                    });
                    callback(list);
                }).catch(() => {});
        },
        handleSelect(item, index) {
            this.addForm.userId = item.userId;
            this.addForm.userName = item.userName;
        },
        deleteAuto: function (index) {
            this.editForm.medicineList.splice(index, 1);
        },
        appendMedicine() {
            this.editForm.medicineList.push({
                "key": this.tempId++
            });
        },
        queryMedicine(queryString, callback) {
            let para = {
                medicineName: queryString,
                medicineStatus: '1'
            };
            api.queryMedicine(para)
                .then(res => {
                    let list = res.returnList.map(item => {
                        item.value = item.medicineName;
                        return item;
                    });
                    callback(list);
                })
                .catch(() => {
                    this.listLoading = false;
                });
        },
        handleSelectMedicine(item, index) {
            this.editForm.medicineList[index].medicineName = item.medicineName;
            this.editForm.medicineList[index].medicineId = item.medicineId;
        },
    },
    mounted() {
        this.userType = localStorage.getItem("userType");
        this.queryCaseInfoByPage();
    }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}

.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.file {
    position: relative;
    display: inline-block;
    background: #63E0EC;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #FFFFFF;
    text-decoration: none;
    text-indent: 0;
    line-height: 30px;
    height: 30px;
}

.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}

.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}
</style>
